﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AjaxChatService.YahooMessenger;

namespace AjaxChatService.Controllers
{
    public class YMUsersController : ApiController
    {
        public HttpResponseMessage GetLogin(string username, string password)
        {
            try
            {
                string requestToken = LoginHelper.GetRequestToken(username, password);
                YMAuthentication accessToken = LoginHelper.GetAccessToken(requestToken);
                AuthParameters.SessionId = LoginHelper.GetSessionId(accessToken);
                AuthParameters.Credentials = accessToken.GetOAuthParameters();

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
            
        }
      
        // log out
        public HttpResponseMessage DeleteSession()
        {
            try
            {
                YMMessagesController.Seq = -1;
                var uri = "http://" + "rcore1.messenger.yahooapis.com" +
                      YMConstants.SessionManagementUrl
                      + "?_method=delete" + "&sid=" + AuthParameters.SessionId + "&" + AuthParameters.Credentials;

                WebRequest request = WebRequest.Create(uri);
                request.ContentType = "application/json; charset=utf-8";
                request.Headers.Add("Authorization", "OAuth");

                HttpUtils.SendHttpPost(request, null, "{}");

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            
        }
    }
}
